/**
 * Created by BIYY on 2017-11-17.
 */
//import axios from 'axios';
const {think} = require('thinkjs');
const conf = require('../../../config/config');
const fetch = require('node-fetch');
const urlUtil = require('../url/index');
let loadingInstance = null;
let req: any = {};
req.ajax = (opt: any) => {
    let option: any = {};
    let setTime = {};
    let time = new Date().valueOf();
    let method = opt.api.method || conf.requestType.get;
    let url = opt.api.url;
    let headers = opt.headers || opt.api.headers || {'Content-Type': 'application/json'};
    if (!url) {
        opt.errorCallBack instanceof Function && opt.errorCallBack('请求链接不能为空!');
        return false;
    }
    let body = {};
    const download = opt.api.download;
    const html = opt.api.html;
    option.headers = headers;
    option.method = method;
    if (download) {
        option.headers['Content-Type'] = 'application/octet-stream';
    }
    option.url = url;
    if (opt.api && opt.api.inject) { //自定义注入器
        option = opt.api.inject(option);
    }

    if (method === conf.requestType.get) { //get请求

        if (opt.data) {
            opt.data.ver = new Date().valueOf();
            option.url = urlUtil.objToUrl(option.url, opt.data);
        }
        think.logger.error('请求路径', option.url);
    } else { //post请求
        think.logger.error('请求路径', url);
        think.logger.error('参数\n', opt.data);
        if (opt.data) {
            opt.data.ver = new Date().valueOf();
            option.data = opt.data;
            body = JSON.stringify(option.data);
        }
    }
    option.params = option.params || opt.params || {};
    return new Promise((resolve, reject) => {
        let options: any = {
            method: option.method,
            headers: option.headers,
        };
        if (method === conf.requestType.post) {
            options.body = body;
        }

        fetch(option.url, options).then((res: any) => {
            if (download) {
                return res.buffer();
            } else if (html) {
                return res.text();
            } else {
                return res.json();
            }
        }).then((response) => {
            req.render(response, opt, setTime, time, resolve);
        }).catch((error) => {
            let response = error.response;
            req.render(response, opt, setTime, time, resolve);
        });
    });
};
req.render = (response: any, opt: any, setTime: any, time: any, resolve: any) => {
    if (response) {
       /* think.logger.error('返回\n', response);*/
        resolve(response);
    } else {
        resolve(null);
        opt.errorCallBack instanceof Function && opt.errorCallBack('网络错误！');
    }
};
module.exports = req;
